﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using BookSourceVerification.common;
using NLog;

namespace BookSourceVerification.utils;

public class HttpVerifyChecker
{
    private static readonly Lazy<HttpClient> _lazyHttpClient = new(() =>
    {

        // 配置SocketsHttpHandler以自定义HttpClient的连接池行为
        var handler = new SocketsHttpHandler
        {
            // 最大连接数
            MaxConnectionsPerServer = 100,
            // 连接存活时间，超过此时间连接将被关闭
            PooledConnectionLifetime = TimeSpan.FromMinutes(5),
            // 连接空闲超时，超过此时间未使用的连接将被关闭
            PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
        };
        HttpClient httpClient = new HttpClient(handler);
        httpClient.Timeout = TimeSpan.FromMilliseconds(Config.TIMEOUT);
        return httpClient;
    });
    private Logger _logger = LogManager.GetCurrentClassLogger();

    public void SetHttpClientTimeout()
    {
        _lazyHttpClient.Value.Timeout = TimeSpan.FromMilliseconds(Config.TIMEOUT);
    }

    public async Task<bool> Check(string url)
    {
        try
        {
            using var httpResponseMessage = await _lazyHttpClient.Value.GetAsync(url);
            var httpStatusCode = (int)httpResponseMessage.StatusCode;
            return httpStatusCode is >= 200 and < 400;
        }
        catch (Exception exception)
        {
            _logger.Error($"url：{url} <——————> exception：{exception}");
            return false;
        }
    }
}